package com.servoy.r3.plugins;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

//import org.mozilla.javascript.Context;
//import org.mozilla.javascript.JavaScriptException;
//import org.mozilla.javascript.Scriptable;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.servoy.j2db.util.Debug;
//import com.servoy.r3.plugins.Base64.InputStream;

public final class Utils {
	
	public static String FILE_SEPARATOR = System.getProperty("file.separator");

	public static String getPathFromFileName(String fullFileName) {

		//int lastSlash = fullFileName.lastIndexOf("\\");
		int lastSlash = fullFileName.lastIndexOf(FILE_SEPARATOR);

		String path = "";

		if (lastSlash >= 0)
			path = fullFileName.substring(0, lastSlash + 1);

		return path;
	}

	public static String getNameWithoutExtensionFromFileName(String fileName) {

		int lastSlash = fileName.lastIndexOf(FILE_SEPARATOR);

		int lastDot = fileName.lastIndexOf(".");
		if (lastDot < 0)
			lastDot = fileName.length();

		String name = fileName.substring(lastSlash + 1, lastDot);

		return name;
	}

	public static String getExtensionFromFileName(String fileName) {

		int lastDot = fileName.lastIndexOf(".");

		String ext = "";

		if (lastDot >= 0)
			ext = fileName.substring(lastDot + 1, fileName.length());

		return ext;
	}

	public static String getModifiedFileName(String fileName, String modifiedExt) {

		String name = Utils.getNameWithoutExtensionFromFileName(fileName);
		String ext = Utils.getExtensionFromFileName(fileName);

		String newname = name + modifiedExt + "." + ext;

		return newname;
	}

	public static String getTempDir(String tempname) {
		String dirr = "";

		Calendar c = Calendar.getInstance();
		Random gen = new Random(c.getTimeInMillis());

		Integer n = new Integer(gen.nextInt(99999));

		dirr = Utils.getPathFromFileName(tempname)
				+ Base64.encodeObject(Utils
						.getNameWithoutExtensionFromFileName(tempname),
						Base64.URL_SAFE) + n.toString();

		dirr = dirr + FILE_SEPARATOR;

		return dirr;
	}

	static public boolean deleteDirectory(File path) {
		if (path.exists()) {
			File[] files = path.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					deleteDirectory(files[i]);
				} else {
					files[i].delete();
				}
			}
		}
		return (path.delete());
	}

	static public File[] getResourceBundleFiles(String path,
			String resourceBundle) {

		Debug.error(resourceBundle, null);

		File dir = new File(path);

		JRXMLResourceBundleFilesFilter filter = new JRXMLResourceBundleFilesFilter(
				resourceBundle);

		File[] list = dir.listFiles(filter);

		return list;
	}

	static public void copyResourceBundleFilesAndAddToZipList(File[] source,
			String destinationPath, ArrayList list) {
		//for (File f : source) {
		for (int i=0; i<source.length; i++)
		{
			File f = source[i];
			try {
				File dest = new File(destinationPath + f.getName());
				copy(f, dest);
				if (list != null)
					list.add(dest.getCanonicalPath());
			} catch (IOException e) {
				Debug.error(e);
			}
		}
	}

	// Copies src file to dst file.
	// If the dst file does not exist, it is created
	static private void copy(File src, File dst) throws IOException {
		FileInputStream in = new FileInputStream(src);
		OutputStream out = new FileOutputStream(dst);

		// Transfer bytes from in to out
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		in.close();
		out.close();
	}

	public static void zipFiles(String destfilename,
			ArrayList listOfFiles) {

		// Create a buffer for reading the files.
		byte[] buf = new byte[1024];

		try {
			// Create the ZIP file.
			String outFilename = destfilename;
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
					outFilename));

			// Compress the files.
			//for (String s : listOfFiles) {
			
			for (int lsti=0; lsti<listOfFiles.size(); lsti++){
				
				String s = (String)listOfFiles.get(lsti);
			
				FileInputStream in = new FileInputStream(s);

				// Add ZIP entry to output stream.
				out.putNextEntry(new ZipEntry(Utils
						.getNameWithoutExtensionFromFileName(s)
						+ "." + Utils.getExtensionFromFileName(s)));

				// Transfer bytes from the file to the ZIP file.
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}

				// Complete the entry.
				out.closeEntry();
				in.close();
			}

			// Complete the ZIP file.
			out.close();
		} catch (IOException e) {
		}
	}

	public static void unzipFile(String zippedFile, String destDir) {
		try {

			// Open the ZIP file
			String inFilename = zippedFile;
			ZipInputStream in = new ZipInputStream(new FileInputStream(
					inFilename));

			ZipEntry entry;

			while ((entry = in.getNextEntry()) != null) {

				// Open the output file
				String outFilename = destDir + entry.getName();
				OutputStream out = new FileOutputStream(outFilename);

				// Transfer bytes from the ZIP file to the output file
				byte[] buf = new byte[1024];
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}

				// Close the streams
				out.close();
			}
			in.close();
		} catch (IOException e) {
		}
	}

	public static String getFilenameDexmled(String filename) {
		String ext = Utils.getExtensionFromFileName(filename);
		String name = Utils.getNameWithoutExtensionFromFileName(Utils
				.getNameWithoutExtensionFromFileName(filename));

		String fn = name + "." + ext;

		return fn;
	}

	public static String getAbsoluteFileName(String path, String filename) {
		String aname = "";

		File n = new File(filename);
		if (n.isAbsolute())
		{
			return filename;
		}

		try {
			File an = new File(path + filename);
			aname = an.getCanonicalPath();
		} catch (IOException e) {
			Debug.error(e);
		}

		
		return aname;
	}

	public static String replaceString(int startPos, int endPos, String str,
			String replacement) {
		String rep = "";

		if (startPos >= endPos)
			return str;

		rep = str.substring(0, startPos);
		rep += replacement;
		rep += str.substring(endPos + 1, str.length());

		return rep;
	}

	public static Element getChildElementForNameAndAttribute(
			Element parentElement, String tagName, String attrName,
			String attrVal) {

		NodeList nodes = parentElement.getElementsByTagName(tagName);

		if (nodes.getLength() > 0) {

			for (int i = 0; i < nodes.getLength(); i++) {
				if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
					Element el = (Element) nodes.item(i);

					Attr atrib = el.getAttributeNode(attrName);
					if (atrib.getValue().compareTo(attrVal) == 0) {
						return el;
					}
				}
			}
		}

		return null;
	}
/*
	public static void evaluateJavaExpression(String expression) {

		Context cx = Context.enter();

		try {
			Scriptable scope = cx.initStandardObjects(null);

			Object result = cx.evaluateString(scope, expression, "<cmd>", 1,
					null);

			String sresult = Context.toString(result);
		} catch (JavaScriptException e) {
			Debug.error(e);
		} finally {
			Context.exit();
		}
	}*/
	
	public static String getNameWithoutQuotes(String name)
	{
		String remname = name;
		
		if (name.startsWith("\""))
			remname = name.substring(1, name.length() - 1);
		
		return remname;
	}
}
